var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var isPosting = false;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: 'artartimages',
  operator: 'upyunadmin2014',
  getSignatureUrl: 'https://api.artart.cn/api.php?ac=signupyun&publickey=' + util.publiccode
});
var oldData = '';
var isEdit = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    minHeight: 0,
    show_addClass_view: false,
    classlysData: [],
    typeIndex: 0,
    selClassly: {},
    uploadImg: [],
    token: "",
    uid: 0,
    imgWH: 0,
    titleValue: '',
    peopleValue: '',
    message: '',
    date: '',
    startDate: '',
    endDate: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    oldData = '';
    isEdit = false;
    if (options.data) {//有数据传过来，说明是编
      wx.showLoading({
        title: '加载中',
      })
      oldData = JSON.parse(options.data);
      isEdit = true;
      console.log("要编辑的数据：", oldData);
    }
    var curDate = new Date();
    var curYear = curDate.getFullYear();
    var curDate_f = util.formatTime(curDate, '-', '');
    var startDate_f = util.formatTime(new Date(curYear - 50, 0, 1), '-', '');
    var endDate_f = util.formatTime(new Date(curYear + 49, 11, 31), '-', '');
    console.log("curDate_f = " + curDate_f + "; startDate_f = " + startDate_f + "; endDate_f = " + endDate_f);
    this.setData({
      date: curDate_f,
      startDate: startDate_f,
      endDate: endDate_f
    });
    this.load();
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token
        });
        that.loadClasslyData();
      }
    });
  },
  load: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight - 40,
          imgWH: (res.windowWidth - 18) / 4 - 12
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(isEdit){
      var photoArray = [];
      if (oldData.photos) {
        photoArray = oldData.photos.split(',');
      }
      var selClassly = { name: oldData.arttype, id: oldData.albumid};
      var people = oldData.people ? (oldData.people.username ? oldData.people.username : oldData.people) :''; 
      this.setData({
        selClassly: selClassly,
        titleValue: oldData.topictitle,
        date: oldData.age,
        peopleValue: people,
        message:oldData.message,
        uploadImg:photoArray
      })
      wx.hideLoading();
    }
  },

  //作品类型选择
  bindPickerSelType: function (e) {
    var index = e.detail.value;
    var selClassLy = this.data.classlysData[index];
    if (selClassLy.id == -1) {
      this.setData({
        show_addClass_view: true
      })
    } else {
      var that = this;
      this.setData({
        typeIndex: index,
        selClassly: that.data.classlysData[index]
      })
    }
  },

  bindDateDate: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  releaseSubmit: function (e) {
    
    if (isPosting) {
      return false;
    }
    isPosting = true;

    var classlyData = this.data.selClassly;//分类
    if (!classlyData || !classlyData.id) {
      app.dialog('请选择文字分类', 'loading');
      isPosting = false;
      return false;
    }

    var title = e.detail.value.title;//标题
    if (!title || title.trim().length <= 0) {
      app.dialog('请输入标题', 'loading');
      isPosting = false;
      return false;
    }
    var date = this.data.date;
    if (!date || date.trim().length <= 0) {
      app.dialog('请选择时间', 'loading');
      isPosting = false;
      return false;
    }
    var people = e.detail.value.people;
    if (!people || people.trim().length <= 0) {
      app.dialog('请输入作者', 'loading');
      isPosting = false;
      return false;
    }
    
    var message = e.detail.value.message;//链接
    if (!message || message.trim().length <= 0) {
      app.dialog('请输入文字', 'loading');
      isPosting = false;
      return false;
    }

    // wx.showLoading({ title: '发布中，请稍等' });
    wx.showLoading({ title: '发布中...' });
    //图片
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var photos_param = "";
    if (photos && photos.length > 0) {
      if (photos.length == 0) {
        app.dialog('请上传图片', 'loading');
        isPosting = false;
        return false;
      }
      //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.imgHost + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');
    }

    var action = "posttopic";
    if (isEdit) {
      action = "edittopic";
    }
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + action + token);//私钥

    var data = {
      ac: action,
      topictype: 9,
      privatekey: privatekey,
      uid: uid,
      postuid: uid,
      topictitle: title,
      people: people,
      albumid: classlyData.id,
      arttype: classlyData.name,
      age: date,
      message: message,
      xcx: 1,
      photos: photos_param
    }
    if (isEdit) {
      data.topicid = oldData.id;
    }
    console.log("文字：", data);
    
    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log(responseData);
        wx.hideLoading();
        if (responseData.data.id) {//你看是不是这个字段判断发布失败还是成功的
          isPosting = false;
          // wx.redirectTo({ url: "/pages/index/index?go=dongtai" });
          wx.reLaunch({ url: "/pages/index/index?go=dongtai" });
        } else {
          app.dialog('发布失败', 'loading');
          isPosting = false;
        }

      },
      fail: function (e) {
        isPosting = false;
        wx.hideLoading();
      }
    });
  },
  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }
    
    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFilePaths = res.tempFilePaths;
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              // jobj.put("url", recordUrl);
              // jobj.put("name", imgFileName);
              // jobj.put("type", resJob.optString("mimetype"));
              // jobj.put("size", resJob.optInt("file_size"));
              // jobj.put("hash", resJob.optString("sign"));
              // jobj.put("extension", resJob.optString("image-type"));
              // jobj.put("save_path", savePath);
              // jobj.put("save_name", savename);
              // jobj.put("width", resJob.optInt("image-width"));
              // jobj.put("height", resJob.optInt("image-height"));
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  addClassEdit: function (e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      className: e.detail.value
    })
  },

  hiddenEditView: function () {
    this.setData({
      show_addClass_view: false,
    });
  },

  addClassAction: function () {
    var className = this.data.className;
    if (className == '中文|English') {
      app.dialog("请输入分类名字", 'loading');
      return;
    }
    if (className.indexOf('|') <= 0 || className.indexOf('|') == className.length - 1) {
      app.dialog("请使用 '|' 分隔中、英文名", 'loading');
      return;
    }
    this.addClassly();
  },

  loadClasslyData: function () {
    var that = this;
    var uid = this.data.uid;
    var params = '';
    var actionItem = '';
    params = {
      ac: "getalbum",
      publickey: util.publiccode,
      uid: uid,
      type: 3
    }
    console.log("getalbum params: ", params);
    util.api({

      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("文字类别：", result);
        
        if (result.msg) {
          var addData = [{
            name: "新增分类",
            id: -1
          }];
          that.setData({
            classlysData: addData,
          });
        } else {
          that.setData({
            classlysData: result
          });
        }

      }
    });
  },

  addClassly: function () {
    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'addalbum' + token);//私钥

    var params = {
      ac: "addalbum",
      privatekey: privatekey,
      name: that.data.className,
      uid: uid,
      type: 3
    }
    console.log("addalbum params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("add作品类别：", result);
        if (result.msg) {

        } else {
          that.setData({
            classlysData: result,
            show_addClass_view: false,
            selClassly: result[0]
          });
        }

      }
    });
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // }
})